package com.cqust.dao;

import com.cqust.entity.Card;
import com.cqust.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class CardDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public int insert(Card card)
    {
        String sql="insert into card(sid,sno,name,cno,balance,lastUseTime) values (?,?,?,?,?,?)";
//        sql=String.format(sql,
//                student.getSno(),
//                student.getName(),
//                student.getAge(),
//                student.getMajor());
        Object[] objects=new Object[]{
                card.getSid(),
                card.getSno(),
                card.getName(),
                card.getCno(),
                card.getBalance(),
                card.getLastUseTime()
        };
        jdbcTemplate.update(sql,objects);
        sql="select * from card where sid=(select max(sid) from card)";
        RowMapper<Card> rm=new BeanPropertyRowMapper<Card>(Card.class);
        Card card1=jdbcTemplate.queryForObject(sql,rm);
        card.setSid(card1.getSid());
        return card1.getSid();
    }

    public int updateById(Card card)
    {
        String sql="update card set balance=? where sno=?";
        Object[] objects=new Object[]{
                card.getBalance(),
                card.getSno()
        };
        jdbcTemplate.update(sql,objects);
        return 1;
    }

    public int deleteById(int id)
    {
        String sql="delete from card where cid=?";
        jdbcTemplate.update(sql,id);
        return 1;
    }

    public Card selectById(int id)
    {
        String sql="SELECT * FROM card where cid=?";
        RowMapper<Card> rm=new BeanPropertyRowMapper<Card>(Card.class);
        return jdbcTemplate.queryForObject(sql,rm,id);
    }

    public List<Card> selectByCondition(String strWhere)
    {
        String sql="SELECT * FROM card ";
        if(strWhere.trim().length()>0)
        {
            sql=sql+"where "+strWhere;
        }
        RowMapper<Card> rm=new BeanPropertyRowMapper<Card>(Card.class);
        return jdbcTemplate.query(sql,rm);
    }
}
